package com.vnp.vchat.version2;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.telpoo.frame.ui.BetaBaseActivity;
import com.turbomanage.httpclient.HttpResponse;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpBasicClientHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonAsyncCallback;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.task.Task;
import com.vnp.vchat.task.TaskType;
import com.vnp.vchat.util.Common;
import com.vnp.vchat.util.KeyboardHelper;
import com.vnp.vchat.util.PreferenceHelper;
import com.vnp.vchat.util.Utils;

public class NhapPassActivity extends BetaBaseActivity implements OnClickListener,TaskType {

	TextView title, titleNhapPass;
	EditText edtTk;
	Button btnTieptuc;

	String name, userName;
	PreferenceHelper preferenceHelper;
	ProgressBar progressBar;
	Dialog dS;
	ArrayList<String> list = new ArrayList<String>();
	MySQLiteHelper db;

	ProgressDialog progressDialog = null;

	Runnable r = new Runnable() {

		@Override
		public void run() {
			gotoMain();
		}
	};
	Handler mHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_nhap_pass);

		preferenceHelper = new PreferenceHelper(this);
		db = new MySQLiteHelper(NhapPassActivity.this);

		name = getIntent().getStringExtra("name");
		userName = getIntent().getStringExtra("username");

		progressBar = (ProgressBar) findViewById(R.id.progressBar1);

		title = (TextView) findViewById(R.id.title);
		titleNhapPass = (TextView) findViewById(R.id.txt_nhap_pass);
		edtTk = (EditText) findViewById(R.id.edt_mat_khau);
		btnTieptuc = (Button) findViewById(R.id.btn_tieptuc);

		khoiTaoCacControlHienThi();
		setSuKienChoBanPhim();

		setFont();
		KeyboardHelper.displaySoftKeyboard(NhapPassActivity.this, edtTk);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			KeyboardHelper.displaySoftKeyboard(NhapPassActivity.this, edtTk);
			return true;
		}
		return false;
	}

	void setFont() {
		title.setTypeface(Utils.getTypefaceBold(NhapPassActivity.this));
		edtTk.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
		btnTieptuc.setTypeface(Utils.getTypefaceMedium(NhapPassActivity.this));
		titleNhapPass.setTypeface(Utils
				.getTypefaceRegular(NhapPassActivity.this));
	}

	void setSuKienChoBanPhim() {
		edtTk.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT) {
					checkPass();
					return true;
				}
				return false;
			}
		});
	}

	void khoiTaoCacControlHienThi() {
		title.setText("Đăng nhập");
		titleNhapPass.setText(Html.fromHtml("Chào mừng <font color='#0070CC'>"
				+ name + "</font>."));
		btnTieptuc.setOnClickListener(this);
		btnTieptuc.setText("Tiếp tục");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_tieptuc:
			checkPass();
			break;
		// case R.id.btn_thoat_tk:
		// btnTieptuc.setText("Đang đồng bộ...");
		// dS.dismiss();
		// showProgressDialog();
		// UpdateContactAsyn asyn = new UpdateContactAsyn();
		// asyn.execute("");
		// break;
		case R.id.btn_ko:
			dS.dismiss();
			mHandler.removeCallbacks(r);
			mHandler.postDelayed(r, 300);
			break;
		default:
			break;
		}
	}

	void checkPass() {
		
		com.telpoo.frame.utils.Utils.saveStringSPR("pp", edtTk.getText().toString(), NhapPassActivity.this);
		
		if (edtTk.getText().toString().equals("")) {
			Toast.makeText(NhapPassActivity.this,
					"Mật khẩu không được để trống!", Toast.LENGTH_SHORT).show();
		} else {
			login();
		}
	}

	void capnhatDanhba() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Utils.getContact(NhapPassActivity.this, 100, 0);
				sendContactHttp();
			}
		}).start();
	}

	void sendContactHttp() {
		
		list = db.getPhoneFromDB();
		JSONArray jsonArray = new JSONArray(list);
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						Log.i("DATA", "Cap nhat danh ba loi");
						gotoMain();
					}

					@Override
					public void onSuccess(JSONObject re) {
						Log.i("DATA",
								"Cap nhat danh ba thanh cong :" + re.toString());
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(NhapPassActivity.this,
										"Cập nhật hoàn thành",
										Toast.LENGTH_SHORT).show();
							}
						});
						gotoMain();
					}
				});
		httpClientHelper.sendContact(preferenceHelper.getAdminId(), jsonArray,
				preferenceHelper.getHashSetting());
	}

	void showProgressDialog() {
		progressDialog = new ProgressDialog(NhapPassActivity.this);
		progressDialog.show();
		progressDialog.setContentView(R.layout.custom_progress_dialog);
		progressDialog.setCancelable(false);

		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				progressDialog.dismiss();
			}
		}, 90000);
	}

	void login() {
		progressBar.setVisibility(View.VISIBLE);
		KeyboardHelper.hideSoftKeyboard(NhapPassActivity.this);
		btnTieptuc.setText("Đang đăng nhập...");
		edtTk.setEnabled(false);
		btnTieptuc.setClickable(false);

		String hash = Utils.MD5("" + Common.KEY_HTTP + "|" + "" + userName
				+ "|" + "" + edtTk.getText().toString());

		Log.i("LOGIN", "HASH: " + hash);

		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(
				new MyJsonAsyncCallback() {

					@Override
					public void onSuccess(HttpResponse httpResponse,
							JSONObject re) {
						int statusCode = httpResponse.getStatus();
						if (statusCode == 200) {
							try {
								int status = re.getInt("status");
								if (status == 1) {

									JSONObject uinf = re.getJSONObject("uinfo");
									JSONObject settings = re
											.getJSONObject("setting");

									preferenceHelper.setUserId(uinf
											.getString("use_sso_id"));
									preferenceHelper.setHash(re
											.getString("hash"));
									preferenceHelper.setHashSetting(re
											.getString("hash_setting"));
									preferenceHelper.setDomainConnect(re
											.getString("domain_connect"));
									preferenceHelper.setPostConnect(re
											.getString("port_connect"));
									preferenceHelper.setDataJoin(re
											.getString("datajoin"));
									preferenceHelper.setSettingNotifi(settings
											.getString("notifi"));
									preferenceHelper.setSettingFeed(settings
											.getString("feed"));
									preferenceHelper.setSettingDisplay(settings
											.getString("showmsg"));
									preferenceHelper.setUserName(uinf
											.getString("name"));
									preferenceHelper.setMyAvatar(uinf
											.getString("imaege"));
									preferenceHelper.setEmail(uinf
											.getString("email"));
									preferenceHelper.setAdminId(re
											.getString("admin_id"));
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											progressBar
													.setVisibility(View.VISIBLE);
											btnTieptuc
													.setText("Đang đồng bộ...");
											// dS.dismiss();
											// showProgressDialog();
											UpdateContactAsyn asyn = new UpdateContactAsyn();
											asyn.execute("");
											// showDialogCapnhatDanhba();
										}
									});
								} else if (status == 0) {
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											progressBar
													.setVisibility(View.GONE);
											btnTieptuc.setText("Tiếp tục");
											edtTk.setEnabled(true);
											btnTieptuc.setClickable(true);
											Toast.makeText(
													NhapPassActivity.this,
													"Sai Mật khẩu.",
													Toast.LENGTH_SHORT).show();
										}
									});
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						} else {
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									progressBar.setVisibility(View.GONE);
									btnTieptuc.setText("Tiếp tục");
									edtTk.setEnabled(true);
									btnTieptuc.setClickable(true);
									Toast.makeText(NhapPassActivity.this,
											"Sai mật khẩu.", Toast.LENGTH_SHORT)
											.show();
								}
							});
						}
					}

					@Override
					public void onFailure(Exception e) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								progressBar.setVisibility(View.GONE);
								btnTieptuc.setText("Tiếp tục");
								edtTk.setEnabled(true);
								btnTieptuc.setClickable(true);
								Toast.makeText(NhapPassActivity.this,
										"Đăng nhập thất bại.",
										Toast.LENGTH_SHORT).show();
							}
						});
					}
				});

		httpBasicClientHelper.loginByPhoneOrEmail(userName, edtTk.getText()
				.toString(), hash, Common.KEY_HTTP);
		
Log.d("mrtran", userName +edtTk.getText().toString()+ hash +Common.KEY_HTTP);
	}

	void gotoMain() {
		
		if(Common.idVchat!=null){
			ArrayList<String> list = new ArrayList<String>();
			list.add(preferenceHelper.getUserId());
			list.add(Common.idVchat);
			list.add(preferenceHelper.getHash());
			Task task = new Task(model, TASK_VGID2CHATID, list, NhapPassActivity.this);
			task.exe();
		}
		
		else{
			Intent t = new Intent(NhapPassActivity.this, MainPanelActivity.class);
			finish();
			Intent broadcastIntent = new Intent();
			broadcastIntent.setAction("HUY");
			sendBroadcast(broadcastIntent);
			startActivity(t);
			overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
		}
	}

	@Override
	public void onBackPressed() {
		closeActivity();
	}

	void closeActivity() {
		finish();
		overridePendingTransition(R.anim.over_main_right,
				R.anim.trans_right_out);
	}

	void showDialogCapnhatDanhba() {
		dS = new Dialog(this);
		dS.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dS.setContentView(R.layout.dialog_thoat_tk);

		TextView txtThoat = (TextView) dS.findViewById(R.id.str_canhbao_thoat);

		txtThoat.setText("Bạn có muốn đồng bộ danh bạ của bạn với vChat không?");

		Button btnThoat = (Button) dS.findViewById(R.id.btn_thoat_tk);
		Button btnKo = (Button) dS.findViewById(R.id.btn_ko);
		dS.show();
		dS.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dS.setCanceledOnTouchOutside(true);
		dS.getWindow().setGravity(Gravity.CENTER);
		dS.show();

		txtThoat.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
		btnThoat.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
		btnKo.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
		// setonclick
		btnThoat.setOnClickListener(this);
		btnKo.setOnClickListener(this);
	}

	private class UpdateContactAsyn extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			Utils.getContact(NhapPassActivity.this, 50, 0);
		
			sendContactHttp();
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// progressDialog.dismiss();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Toast.makeText(NhapPassActivity.this,
							"Cập nhật thành công", Toast.LENGTH_SHORT).show();
				}
			});
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
		mHandler.removeCallbacks(r);
	}
	
	@Override
	public void onSuccess(int taskType, ArrayList<?> list, String msg) {
		super.onSuccess(taskType, list, msg);
		
		Intent t = new Intent(NhapPassActivity.this, MainPanelActivity.class);
		finish();
		Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("HUY");
		sendBroadcast(broadcastIntent);
		startActivity(t);
		overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
		
	}
	
	@Override
	public void onFail(int taskType, String msg) {
		super.onFail(taskType, msg);
		
		showToast(""+msg);
		
		Intent t = new Intent(NhapPassActivity.this, MainPanelActivity.class);
		finish();
		Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("HUY");
		sendBroadcast(broadcastIntent);
		startActivity(t);
		overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
	}
	
	
	

}
